package cn.dxs.adt.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import cn.dxs.adt.R;

/**
 * HEIF图片文件处理类
 */
public class Heic2jpgActivity extends BaseActivity implements View.OnClickListener, View.OnLongClickListener {

    private static final int HANDLER_DATA_HEIF2JPG = 1000;
    private static final int HANDLER_DATA_HEIF2PNG = 1001;
    private static final int HANDLER_DATA_HEIF_DELETE = 1002;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private Button mBtn_heif2jpg;
    private Button mBtn_heif2png;
    private Button mBtn_heif2jpg_dir;
    private Button mBtn_heif2png_dir;
    private Button mBtn_heif_delete;
    private boolean isExecutionComplete = true;//执行完成
    private int success = 0;//成功
    private int fail = 0;//失败
    private int invalidPath = 0;//无效路径
    private int noHEIF = 0;//非HEIF文件
    private String mHeifPathCache;//缓存地址

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_heic2jpg);
        initToolBar(toolbar, true, getTitle());
//        String heicFile = "/storage/emulated/0/aaa/IMG_0131.HEIC";
//        String jpgFile = "/storage/emulated/0/aaa/IMG_0131.jpg";
        init();
    }

    private void init() {
        initView();
        initData();
    }

    private void initView() {
        mBtn_heif2jpg = findViewById(R.id.btn_heif2jpg);
        mBtn_heif2png = findViewById(R.id.btn_heif2jpg);
        mBtn_heif2jpg_dir = findViewById(R.id.btn_heif2jpg_dir);
        mBtn_heif2png_dir = findViewById(R.id.btn_heif2jpg_dir);
        mBtn_heif_delete = findViewById(R.id.btn_heif_delete);

        mBtn_heif2jpg.setOnClickListener(this);
        mBtn_heif2png.setOnClickListener(this);
        mBtn_heif2jpg_dir.setOnClickListener(this);
        mBtn_heif2png_dir.setOnClickListener(this);
        mBtn_heif_delete.setOnClickListener(this);

        mBtn_heif2jpg.setOnLongClickListener(this);
        mBtn_heif2png.setOnLongClickListener(this);
        mBtn_heif2jpg_dir.setOnLongClickListener(this);
        mBtn_heif2png_dir.setOnLongClickListener(this);
        mBtn_heif_delete.setOnLongClickListener(this);
    }

    private void initData() {

    }

    private void initFlag() {
        isExecutionComplete = false;
        success = 0;
        fail = 0;
        invalidPath = 0;
        noHEIF = 0;
    }

    @Override
    protected void parserMessage(Message msg) {
        super.parserMessage(msg);
        switch (msg.what) {
            case HANDLER_DATA_HEIF2JPG:
                mBtn_heif2jpg_dir.setText(String.valueOf(msg.obj));
                break;
            case HANDLER_DATA_HEIF2PNG:
                mBtn_heif2png_dir.setText(String.valueOf(msg.obj));
                break;
            case HANDLER_DATA_HEIF_DELETE:
                mBtn_heif_delete.setText(String.valueOf(msg.obj));
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_heif2jpg:
                selectPicture(1);
                break;
            case R.id.btn_heif2png:
                selectPicture(2);
                break;
            case R.id.btn_heif2jpg_dir:
                selectPicture(3);
                break;
            case R.id.btn_heif2png_dir:
                selectPicture(4);
                break;
            case R.id.btn_heif_delete:
                selectPicture(5);
                break;
        }
    }

    @Override
    public boolean onLongClick(View v) {
        if (TextUtils.isEmpty(mHeifPathCache)) return false;
        initFlag();
        switch (v.getId()) {
            case R.id.btn_heif2jpg:
                heif2jpg(mHeifPathCache);
                break;
            case R.id.btn_heif2png:
                heif2png(mHeifPathCache);
                break;
            case R.id.btn_heif2jpg_dir:
                heif2jpg_dir(mHeifPathCache);
                break;
            case R.id.btn_heif2png_dir:
                heif2png_dir(mHeifPathCache);
                break;
            case R.id.btn_heif_delete:
                heifDelete(mHeifPathCache);
                break;
        }
        return true;
    }

    private void selectPicture(int requestCode) {
        if (!isExecutionComplete) {
            showToast("暂未执行完成，请稍后再试！");
            return;
        }
        initFlag();
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, requestCode);
    }

    private void heif2jpg(String heifPath) {
        int result = convertImage(heifPath, Bitmap.CompressFormat.JPEG);
        if (result == 0) {//0：成功 1：失败 2：无效路径 3：非HEIF文件
            Toast.makeText(this, "转换成功", Toast.LENGTH_SHORT).show();
        } else if (result == 1) {
            Toast.makeText(this, "转换失败", Toast.LENGTH_SHORT).show();
        } else if (result == 2) {
            Toast.makeText(this, "无效路径", Toast.LENGTH_SHORT).show();
        } else if (result == 3) {
            Toast.makeText(this, "非HEIF文件", Toast.LENGTH_SHORT).show();
        }
        isExecutionComplete = true;
    }

    private void heif2png(String heifPath) {
        int result = convertImage(heifPath, Bitmap.CompressFormat.PNG);
        if (result == 0) {//0：成功 1：失败 2：无效路径 3：非HEIF文件
            Toast.makeText(this, "转换成功", Toast.LENGTH_SHORT).show();
        } else if (result == 1) {
            Toast.makeText(this, "转换失败", Toast.LENGTH_SHORT).show();
        } else if (result == 2) {
            Toast.makeText(this, "无效路径", Toast.LENGTH_SHORT).show();
        } else if (result == 3) {
            Toast.makeText(this, "非HEIF文件", Toast.LENGTH_SHORT).show();
        }
        isExecutionComplete = true;
    }

    private void heif2jpg_dir(String heifPath) {
        File file = new File(heifPath);
        File[] files = file.getParentFile().listFiles();
        int total = files.length;
        int completed = 0;
        for (File f : files) {
            if (f.isFile()) {
                int result = convertImage(f.getAbsolutePath(), Bitmap.CompressFormat.JPEG);
                if (result == 0) {//0：成功 1：失败 2：无效路径 3：非HEIF文件
                    success++;
                } else if (result == 1) {
                    fail++;
                } else if (result == 2) {
                    invalidPath++;
                } else if (result == 3) {
                    noHEIF++;
                }
            } else {
                invalidPath++;
            }
            String obj = "HEIF转JPG(目录)转换中请勿做其他操作(" + (completed++) + "/" + total + ")\n" + "成功:" + success + " 失败:" + fail + " 无效路径:" + invalidPath + " 非HEIF文件:" + noHEIF;
            sendMsg(HANDLER_DATA_HEIF2JPG, obj);
        }
        String obj = "HEIF转JPG(目录)已全部完成(" + (completed++) + "/" + total + ")\n" + "成功:" + success + " 失败:" + fail + " 无效路径:" + invalidPath + " 非HEIF文件:" + noHEIF;
        sendMsg(HANDLER_DATA_HEIF2JPG, obj);
        isExecutionComplete = true;
    }

    private void heif2png_dir(String heifPath) {
        File file = new File(heifPath);
        File[] files = file.getParentFile().listFiles();
        int total = files.length;
        int completed = 0;
        for (File f : files) {
            if (f.isFile()) {
                int result = convertImage(f.getAbsolutePath(), Bitmap.CompressFormat.PNG);
                if (result == 0) {//0：成功 1：失败 2：无效路径 3：非HEIF文件
                    success++;
                } else if (result == 1) {
                    fail++;
                } else if (result == 2) {
                    invalidPath++;
                } else if (result == 3) {
                    noHEIF++;
                }
            } else {
                invalidPath++;
            }
            String obj = "HEIF转PNG(目录)转换中请勿做其他操作(" + (completed++) + "/" + total + ")\n" + "成功:" + success + " 失败:" + fail + " 无效路径:" + invalidPath + " 非HEIF文件:" + noHEIF;
            sendMsg(HANDLER_DATA_HEIF2PNG, obj);
        }
        String obj = "HEIF转PNG(目录)已全部完成(" + (completed++) + "/" + total + ")\n" + "成功:" + success + " 失败:" + fail + " 无效路径:" + invalidPath + " 非HEIF文件:" + noHEIF;
        sendMsg(HANDLER_DATA_HEIF2PNG, obj);
        isExecutionComplete = true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data == null) return;
            String heifPath = data.getData().getLastPathSegment();
            mHeifPathCache = heifPath;
            if (requestCode == 1) {
                heif2jpg(heifPath);
            } else if (requestCode == 2){
                heif2png(heifPath);
            } else if (requestCode == 3){
                new Thread(){
                    @Override
                    public void run() {
                        heif2jpg_dir(heifPath);
                    }
                }.start();
            } else if (requestCode == 4){
                new Thread(){
                    @Override
                    public void run() {
                        heif2png_dir(heifPath);
                    }
                }.start();
            } else if (requestCode == 5) {
                new Thread(){
                    @Override
                    public void run() {
                        heifDelete(heifPath);
                    }
                }.start();
            }
        } else {
            isExecutionComplete = true;
        }
    }

    private void heifDelete(String heifPath) {
        File file = new File(heifPath);
        File[] files = file.getParentFile().listFiles();
        int total = files.length;
        int completed = 0;
        for (File f : files) {
            String path = f.getAbsolutePath().toLowerCase();
            if (f.isFile()) {
                if (path.endsWith(".heif") || path.endsWith(".heic")) {
                    if (f.delete()) {
                        success++;
                    } else {
                        fail++;
                    }
                } else {
                    noHEIF++;
                }
            } else {
                invalidPath++;
            }
            String obj = "删除HEIF文件(目录)删除中请勿做其他操作(" + (completed++) + "/" + total + ")\n" + "成功:" + success + " 失败:" + fail + " 无效路径:" + invalidPath + " 非HEIF文件:" + noHEIF;
            sendMsg(HANDLER_DATA_HEIF_DELETE, obj);
        }
        String obj = "删除HEIF文件(目录)已全部完成(" + (completed++) + "/" + total + ")\n" + "成功:" + success + " 失败:" + fail + " 无效路径:" + invalidPath + " 非HEIF文件:" + noHEIF;
        sendMsg(HANDLER_DATA_HEIF_DELETE, obj);
        isExecutionComplete = true;
    }

    /**
     *
     * @param heifPath
     * @param format
     * @return 0：成功 1：失败 2：无效路径 3：非HEIF文件
     */
    public int convertImage(String heifPath, Bitmap.CompressFormat format) {
        int result = 1;
        File file = new File(heifPath);
        if (!file.exists()) {
            return 2;
        }
        if (!heifPath.toLowerCase().endsWith(".heif") && !heifPath.toLowerCase().endsWith(".heic")) {
            return 3;
        }
        if (file.isFile()) {
            Bitmap b = BitmapFactory.decodeFile(heifPath);
            //bitmap旋转90度
            Matrix m = new Matrix();
            m.setRotate(90, (float) b.getWidth() / 2, (float) b.getHeight() / 2);
            Bitmap bitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);
            if (bitmap != null) {
                String name = format.toString().toLowerCase();
                if (name.equals("jpeg")) name = "jpg";
                File saveFile = new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().length() - 4) + name);
                if (saveFile.exists() && saveFile.isFile()) return 0;
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(saveFile);
                    bitmap.compress(format, 100, fileOutputStream);
                    fileOutputStream.flush();
                    result = 0;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fileOutputStream != null) {
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return result;
    }
}